package org.madmac.controller.placaRede;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.madmac.controller.validate.Validate;
import org.madmac.faixaIp.FaixaIp;
import org.madmac.faixaIp.FaixaIpDao;
import org.madmac.maquina.MaquinaDao;
import org.madmac.placaRede.PlacaRede;
import org.madmac.placaRede.PlacaRedeBo;
import org.madmac.placaRede.PlacaRedeDao;
import org.madmac.servlet.action.Action;
import org.madmac.servlet.form.Form;
import org.madmac.setor.Setor;
import org.madmac.setor.SetorDao;

/**
 *
 * @author atila camurca
 */
public class PlacaRedeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			  throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			/* 
			out.println("<html>");
			out.println("<head>");
			out.println("<title>Servlet PlacaRedeServlet</title>");
			out.println("</head>");
			out.println("<body>");
			out.println("<h1>Servlet PlacaRedeServlet at " + request.getContextPath () + "</h1>");
			out.println("</body>");
			out.println("</html>");
			 */
		} finally {
			out.close();
		}
	}

	/**
	 * Handles the HTTP <code>GET</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			  throws ServletException, IOException {
		try {
			if (request.getParameter("form") != null) {
            // FORM ADD
				if (Form.ADD.equals(Form.valueOf(request.getParameter("form")))) {
					//System.out.println("PlacaRede ADD");
					List<FaixaIp> listFaixa = FaixaIpDao.getInstance().findFaixaIpLivre();
					int count = listFaixa.size();
					request.setAttribute("faixas", listFaixa);
					request.setAttribute("count", count);
					request.setAttribute("form", Form.ADD);

					if (request.getParameter("tombamento") != null) {
						request.setAttribute("tombamento", request.getParameter("tombamento"));
					}
				}
			}  else if (request.getParameter("action") != null) {
            // ACTION LIST ALL
            if (Action.LIST_ALL.equals(Action.valueOf(request.getParameter("action")))) {
					Integer idSetor = Validate.integerValue(request.getParameter("id_setor"));
					Integer idFaixaIp = Validate.integerValue(request.getParameter("id_faixa_ip"));

					List<Setor> listSetor = SetorDao.getInstance().findAll();
					List<FaixaIp> listFaixa = FaixaIpDao.getInstance().findAll();
					int countSetor = listSetor.size();
					int countFaixa = listFaixa.size();

					request.setAttribute("setores", listSetor);
					request.setAttribute("faixas", listFaixa);
					request.setAttribute("idSetor", idSetor);
					request.setAttribute("countSetor", countSetor);
					request.setAttribute("countFaixa", countFaixa);
					request.setAttribute("idFaixaIp", idFaixaIp);
					request.setAttribute("action", Action.LIST_ALL);

               // se pelo menos um dos dois parametros nao for nulo realiza a busca.
               if (idSetor != null || idFaixaIp != null) {
                  List<PlacaRede> listPlaca = PlacaRedeDao.getInstance().findAll(idSetor, idFaixaIp);
                  request.setAttribute("placas", listPlaca);
               }
				}
			}			
		} catch (Exception e) {
			System.out.println("Erro: " + e.getMessage());
         request.setAttribute("error", e);
			request.setAttribute("action", Action.ERROR);
		} finally {
         RequestDispatcher dispatcher = request.getRequestDispatcher("mac/mac.jsp");
         dispatcher.forward(request, response);
      }
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			  throws ServletException, IOException {
		try {
			// id null, add placa rede.
			if (request.getParameter("id") == null) {
				
				Integer tombamento = null;
				if (request.getParameter("tombamento") != null && !request.getParameter("tombamento").isEmpty()) {
					tombamento = Integer.parseInt(request.getParameter("tombamento"));
				}
				Integer idMaquina = MaquinaDao.getInstance().retrieveIdMaquina(tombamento);
				if (idMaquina != null) {
					PlacaRede placa = new PlacaRede();
					
					if (request.getParameter("mac") != null) {
						placa.setMac(request.getParameter("mac"));
					}
					if (request.getParameter("faixa_ip") != null) {
						placa.getIp().getFaixaIp().setIdFaixa(Integer.parseInt(request.getParameter("faixa_ip")));
					}					
					placa.getMaquina().setIdMaquina(idMaquina);
					placa.setRedeSemFio(Boolean.parseBoolean(request.getParameter("rede_sem_fio")));

					PlacaRedeBo.getInstance().validateAndCreate(placa);

					PlacaRede _placa = PlacaRedeDao.getInstance().findByMac(placa.getMac());
					request.setAttribute("placa", _placa);
					request.setAttribute("action", Action.LIST);
				}  else {
					request.setAttribute("error", new Exception("Máquina (Tombamento) não encontrado."));
					request.setAttribute("action", Action.LIST);
				}
			} else {
				// editar placa rede.
			}
			RequestDispatcher dispatcher = request.getRequestDispatcher("mac/mac.jsp");
			dispatcher.forward(request, response);
		} catch (Exception e) {
			System.out.println("Erro: " + e.getMessage());
			request.setAttribute("error", e);
			request.setAttribute("action", Action.ERROR);
		} finally {
         RequestDispatcher dispatcher = request.getRequestDispatcher("mac/mac.jsp");
         dispatcher.forward(request, response);
      }
	}

	/**
	 * Returns a short description of the servlet.
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}
}
